package cn.xz.zysjz.utils;


import android.net.Uri;

import java.io.File;

import cn.xz.zysjz.base.BaseApplication;
import cn.xz.zysjz.bean.CommonLib;
import cn.xz.zysjz.bean.SetNewUser;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 上传文件到服务器*/
public class UpLoadUtils {

    public  interface PutOk{
        void click(String s);
    }

    public static void to(Uri uri,PutOk putOk){
        Luban.with(BaseApplication.getContext()).load(uri).ignoreBy(100)
                .setTargetDir(getUrlPath())
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }
//test1709345262340.png
                    @Override
                    public void onSuccess(int index, File compressFile) {
                        String mPicUrl = "test" + System.currentTimeMillis() + ".png";
                        RequestBody requestBody = RequestBody.create( MediaType.parse("image/*"),compressFile); //所有图片类型
                        MultipartBody newBody =  new MultipartBody.Builder()
                                .setType(MultipartBody.FORM)
                                .addFormDataPart("file", mPicUrl,requestBody)
                                .build();
                        OkHttpUtils.toPost("http://hualao.icu:9999/file/upload", newBody, new OkHttpUtils.RequestSuccess() {
                            @Override
                            public void success(Object data) {
                                putOk.click(mPicUrl);
                            }

                            @Override
                            public void error() {

                            }
                        }, SetNewUser.class);
                    }

                    @Override
                    public void onError(int index, Throwable e) {

                    }
                }).launch();
    }

    private static String getUrlPath(){
        File externalFilesDir = BaseApplication.getContext().getExternalFilesDir("");
        File customFile = new File(externalFilesDir.getAbsolutePath(), "Sandbox");
        if (!customFile.exists()) {
            customFile.mkdirs();
        }
        return customFile.getAbsolutePath() + File.separator;
    }
}
